package work1;

import java.util.LinkedList;
import java.util.Queue;

public class RR {
private Queue<Job> jobQueue;
private int timeSlice;

//双向链表是一种灵活的数据结构，可以方便地在队列头部和尾部进行操作。
// 在RR调度算法中，每次作业执行完毕后，都需要将其重新加入队列的尾部，双向链表可以方便地实现这一点。
public RR(int timeSlice){
	jobQueue = new LinkedList<>();
	this.timeSlice = timeSlice;
}

public void addJob(Job job){
	jobQueue.add(job);
}

public void schedule(){
	int currentTime = 0;
	while(!jobQueue.isEmpty()){
		Job currentJob = jobQueue.poll();
		System.out.println("作业名："+currentJob.jobName);
		System.out.println("到达时间："+currentJob.arrivalTime);
		System.out.println("执行时间："+currentJob.conductTime);

		if(currentTime < currentJob.arrivalTime){
			currentTime = currentJob.arrivalTime;
		}

		if(currentJob.remainTime > timeSlice){
			currentTime += timeSlice;
                currentJob.remainTime -= timeSlice;
			System.out.println("时间片结束，作业剩余时间："+currentJob.remainTime);
                jobQueue.add(currentJob);// 时间片结束后，需要重新加入队列
			} else {
			currentTime += currentJob.remainTime;
                System.out.println("作业执行完毕："+currentTime);
		}

		System.out.println();
    }
	}

	public static void main(String[] args) {
		RR rr = new RR(2);
        Job job1 = new Job("作业一", 0, 6);
        Job job2 = new Job("作业二", 2, 4);
        Job job3 = new Job("作业三", 4, 8);
        Job job4 = new Job("作业四", 6, 10);
        Job job5 = new Job("作业五", 8, 5);

        rr.addJob(job1);
        rr.addJob(job2);
        rr.addJob(job3);
		rr.addJob(job4);
		rr.addJob(job5);
        rr.schedule();
	}
}

